<script>
	import Vue from 'vue'
	export default {
		data() {
			return {
				timer: null,
				serveTime: 0
			}
		},
		onLaunch: function() {
			this.$store.commit('initApp')
			uni.getSystemInfo({
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45
					}
					// #endif
					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight
					let custom = wx.getMenuButtonBoundingClientRect()
					Vue.prototype.Custom = custom
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight
					// #endif
					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight
					// #endif
					let unitRatio = 750 / uni.getSystemInfoSync().windowWidth
					Vue.prototype.StatusBarRpx = Vue.prototype.StatusBar * unitRatio
					Vue.prototype.CustomBarRpx = Vue.prototype.CustomBar * unitRatio
					Vue.prototype.unitRatio = unitRatio
					Vue.mixin({
						data() {
							return {
								StatusBar: Vue.prototype.StatusBar, //状态栏高度(px)
								CustomBar: Vue.prototype.CustomBar, //整个标题栏高度(px)
								StatusBarRpx: Vue.prototype.StatusBarRpx, //状态栏高度(rpx)
								CustomBarRpx: Vue.prototype.CustomBarRpx, //整个标题栏高度(rpx)
							}
						},
					})
				},
			})
			// #ifdef APP-PLUS
			// 锁定屏幕显示方向为竖屏正方向
			plus.screen.lockOrientation('portrait-primary')
			// 推送服务
			// plus.push.addEventListener('click', (message) => {
			//   this.pushCallback(message)
			// })
			// #endif
			global.token && this.$store.dispatch('getCartList')

			this.initializeSocket();
			uni.$on('appLoginSuccess', () => {
				uni.closeSocket();
				this.initializeSocket();
			})
			
			if (!uni.getStorageSync('is_camera')) {
				uni.setStorageSync('is_camera', 0);
			}
			if (!uni.getStorageSync('is_phone')) {
				uni.setStorageSync('is_phone', 0);
			}
			if (!uni.getStorageSync('is_storage')) {
				uni.setStorageSync('is_storage', 0);
			}
		},
		onShow: function() {
			console.log('APP Show')
			// #ifdef APP-PLUS
			// 获取参数
			const args = plus.runtime.arguments
			if (args) {
				plus.runtime.arguments = null
				plus.runtime.arguments = ''
				let params_str = args.split('?')[1]
				if (params_str) {
					let params = params_str.split('&').reduce(function(total, item) {
						let arr = item.split('=')
						total[arr[0]] = arr[1]
						return total
					}, {})
					console.log('params', params)
					// params 参数: path 跳转路径 options 参数
					uni.navigateTo({
						url: `${params.path}?goods_id=${params.goods_id}&activity_id=${params.activity_id}&sku_id=${params.sku_id}&bargain_id=${params.bargain_id}`,
					})
				}
			}
			// #endif
			// android  ios
			global.platform = uni.getSystemInfoSync().platform;
		},
		onHide: function() {
			// 用户退出app时，把二次验证状态改为true
			console.log('APP Hide');
		},
		methods: {
			// 推送回调
			pushCallback(message) {
				this.$urouter.navigateTo('/pages/service-message/message/message-type/index')
			},
			initializeSocket() {
				let _this = this;
				if (global.token) {
					// 链接socket
					uni.connectSocket({
						url: 'wss:app.yuntaikongtiao.com:8282',
						header: {
							'content-type': 'application/json'
						},
						success: function(res) {
							console.log(res);
						},
						fail: function(err) {
							console.log(err);
						}
					});
					// 接收socket消息
					uni.onSocketOpen(res => {
						console.log(res);
						_this.TimeOut();
						// socket 断开链接后尝试重新链接
						uni.onSocketError(err => {
							console.log(err)
							if (this.timer) {
								clearInterval(this.timer);
							}
							uni.closeSocket();
							this.initializeSocket();
						});

						uni.sendSocketMessage({
							data: JSON.stringify({
								event: 'bind',
								user_id: global.userInfo.id
							})
						});
						uni.onSocketMessage(onMessage => {
							// console.log(onMessage)
							// let onMessageJson =onMessage.data;
							let onMessageJson = JSON.parse(onMessage.data);
							_this.serveTime = new Date().getTime();
							// console.log(onMessageJson)
							// chat_type 7 解散群聊 8 系统消息 9 监听有新的好友申请  10 入群验证
							// if(onMessageJson.msg_type == 8) return  console.log("系统消息");
							// if (onMessageJson.content == "群主解散了群") {
							// 	uni.$emit("upDataList")
							// }
							// if (onMessageJson.chat_type == 10) return this.postJoinList();
							// if (onMessageJson.chat_type == 9) return this.postApplyData();
							// return
							// if (onMessageJson.type == 'signIn') return this.upLoadClientID(onMessageJson
							// 	.clientID);
							// if (onMessageJson.msg_type == 4 || onMessageJson.msg_type == 5) {
							// 	onMessageJson.content = JSON.parse(onMessageJson.content);
							// }
							// this.addHistory(onMessageJson);
							// const top = 99999;
							if (onMessageJson.event == 'send') {
								uni.$emit("newMsg", {
									onMessageJson
								});
							}
						})
						// 定时发送心跳消息避免断开
						this.timer = setInterval(() => {
							uni.sendSocketMessage({
								data: JSON.stringify({
									event: 'ping'
								})
							});
						}, 15000)
					})

				}
			},
			//超时响应
			TimeOut() {
				let _this = this;
				setTimeout(function() {
					let times = new Date().getTime();
					if ((times - _this.serveTime) > 15000) {
						//以下做超时后的操作
						if (_this.timer) {
							clearInterval(_this.timer);
						}
						uni.closeSocket();
						_this.initializeSocket();
					}
				}, 500);
			},
			// 订单事件通知
			orderChat() {
				/**
				 * msg_type 信息类型  msg_type  1 创建订单  2  支付成功  3、取消  4、售后  5、提醒发货
				 * */
				let _this = this;
				let message = '';
				message = {
					event: 'order',
					from_user_id: global.userInfo.id,
					to_user_id: global.userInfo.kefu_id,
					msg_type: global.order_msg_type,
					content: ''
				}
			
				// 发送消息
				uni.sendSocketMessage({
					data: JSON.stringify(message),
					success: (res) => {
						console.log(res)
					},
					fail: (err) => {
						console.log(err)
						if (_this.timer) {
							clearInterval(_this.timer);
						}
						uni.closeSocket();
						_this.initializeSocket();
					}
				});
			},




			// #ifdef APP-PLUS
			// 权限检查
			checkPermissions() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					// 判断是Android
					var main = plus.android.runtimeMainActivity()
					var pkName = main.getPackageName()
					var uid = main.getApplicationInfo().plusGetAttribute('uid')
					var NotificationManagerCompat = plus.android.importClass(
						'android.support.v4.app.NotificationManagerCompat')
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled()
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
					if (!areNotificationsEnabled) {
						uni.showModal({
							title: this.$t('通知权限开启提醒'),
							content: this.$t('您还没有开启通知权限，无法接受到消息通知，是否前往设置？'),
							success: function(res) {
								if (res.confirm) {
									var Intent = plus.android.importClass('android.content.Intent')
									var Build = plus.android.importClass('android.os.Build')
									//android 8.0引导
									if (Build.VERSION.SDK_INT >= 26) {
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
										intent.putExtra('android.provider.extra.APP_PACKAGE', pkName)
									} else if (Build.VERSION.SDK_INT >= 21) {
										//android 5.0-7.0
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
										intent.putExtra('app_package', pkName)
										intent.putExtra('app_uid', uid)
									} else {
										//(<21)其他--跳转到该应用管理的详情页
										intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
										var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
										intent.setData(uri)
									}
									// 跳转到该应用的系统通知设置页
									main.startActivity(intent)
								}
							},
						})
					}
				} else if (plus.os.name == 'iOS') {
					// 判断是IOS
					var isOn = undefined
					var types = 0
					var app = plus.ios.invoke('UIApplication', 'sharedApplication')
					var settings = plus.ios.invoke(app, 'currentUserNotificationSettings')
					if (settings) {
						types = settings.plusGetAttribute('types')
						plus.ios.deleteObject(settings)
					} else {
						types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes')
					}
					plus.ios.deleteObject(app)
					isOn = 0 != types
					if (isOn == false) {
						uni.showModal({
							title: this.$t('通知权限开启提醒'),
							content: this.$t('您还没有开启通知权限，无法接受到消息通知，是否前往设置？'),
							success: function(res) {
								if (res.confirm) {
									var app = plus.ios.invoke('UIApplication', 'sharedApplication')
									var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:')
									plus.ios.invoke(app, 'openURL:', setting)
									plus.ios.deleteObject(setting)
									plus.ios.deleteObject(app)
								}
							},
						})
					}
				}
				// #endif
			},
			// #endif
		},
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
	/* #ifndef APP-PLUS-NVUE */
	@import './style/icon.css';
	@import './style/main.css';
	@import './style/animation.css';
	@import './style/iconfont.css';
	@import './style/common.scss';
	@import './style/diyStyle.scss';
	/* #endif */
</style>